#!/usr/bin/env bash

# Set up prompt; color-coded by login type.
#
# copy to /etc/profile.d/prompt.sh to make it the default prompt
# for the system.
#===============================================================
THIS_TTY=$(ps aux | grep "$$" | grep "bash" | awk '{ print $7 }')
SESS_SRC=( $(who | grep "$USER" | grep "$THIS_TTY" | awk '{ print $6 }') )
SESS_SRC=${SESS_SRC[0]} # if more than 1 match, keep only first entry

SSH_FLAG=0
SSH_IP=$(echo $SSH_CLIENT | awk '{ print $1 }')
if [ $SSH_IP ] ; then
    SSH_FLAG=1
fi
SSH2_IP=$(echo $SSH2_CLIENT | awk '{ print $1 }')
if [ $SSH2_IP ] ; then
    SSH_FLAG=1
fi
if [ $SSH_FLAG -eq 1 ] ; then
    CONN=ssh
elif [ -z $SESS_SRC ] ; then
    CONN=lcl
elif [ $SESS_SRC = "(:0.0)" -o $SESS_SRC = "" ] ; then
    CONN=lcl
else
    CONN=tel
fi

# Okay...Now who we be?
if [ "$(whoami)" = "root" ] ; then
    USR=priv
else
    USR=nopriv
fi

# Color escape sequences.
UNDERLINE='\[\033[4m\]';
NO_COLOR='\[\033[0m\]';
# foreground color              # foreground color              # background color
BLACK='\[\033[0;30m\]';         DARK_GRAY='\[\033[1;30m\]';     BBLACK='\[\033[40m\]';
RED='\[\033[0;31m\]';           LIGHT_RED='\[\033[1;31m\]';     BRED='\[\033[41m\]';
GREEN='\[\033[0;32m\]';         LIGHT_GREEN='\[\033[1;32m\]';   BGREEN='\[\033[42m\]';
BROWN='\[\033[0;33m\]';         YELLOW='\[\033[1;33m\]';        BBROWN='\[\033[43m\]';
BLUE='\[\033[0;34m\]';          LIGHT_BLUE='\[\033[1;34m\]';    BBLUE='\[\033[44m\]';
PURPLE='\[\033[0;35m\]';        LIGHT_PURPLE='\[\033[1;35m\]';  BPURPLE='\[\033[45m\]';
CYAN='\[\033[0;36m\]';          LIGHT_CYAN='\[\033[1;36m\]';    BCYAN='\[\033[46m\]';
LIGHT_GRAY='\[\033[0;37m\]';    WHITE='\[\033[1;37m\]';         BGRAY='\[\033[47m\]';

# Are we an interactive shell?
if [ "$PS1" ]; then
    #Set some prompts...
    if [ $CONN = lcl -a $USR = nopriv ] ; then   # local, user
        COLOR=$GREEN;
        PS1="${COLOR}[${NO_COLOR}\u@\h:\W/${COLOR}]${NO_COLOR}\$ ";
    elif [ $CONN = lcl -a $USR = priv ] ; then   # local, root
        COLOR=$LIGHT_RED;
        PS1="${COLOR}[${NO_COLOR}\u@\h:\W/${COLOR}]${NO_COLOR}# ";
    elif [ $CONN = ssh -a $USR = nopriv ] ; then # ssh, user
        COLOR=$LIGHT_PURPLE;
        PS1="${COLOR}[${NO_COLOR}\u@\h:\W/${COLOR}]${NO_COLOR}\$ ";
    elif [ $CONN = ssh -a $USR = priv ] ; then   # ssh, root
        COLOR=$LIGHT_RED;
        PS1="${COLOR}[${NO_COLOR}\u@\h:\W/${COLOR}]${NO_COLOR}# ";
    fi
    export PS1;
fi
